<template>
    <div style="padding:0 10px">
        <div class="header">
            <fund-query-condition
                @comReturn="comReturn"
                @handleButton="handleButton"
                :showSearchParams="showSearchParams"
                :isFirst="isFirst && activeValue === 'fund-query'"
                immediate="true"
            ></fund-query-condition>
        </div>
        <div>
            <vxe-table
                :header-cell-style="{ backgroundColor: '#e8f3ff', padding: '4px 0' }"
                :footer-cell-style="{ backgroundColor: '#e8f3ff', padding: '4px 0' }"
                :data="tableData"
                :key="tableKey + 'tableKey'"
                v-loading="loading"
                v-table-top="page.currentPage"
                border
                stripe
                resizable
                :auto-resize="true"
                show-footer
                :footer-method="getSummaries"
                :sort-config="{
                    defaultSort: { field: sortProp, order: sortOrder, orders: ['desc', 'asc', null] },
                    remote: true,
                }"
                highlight-current-row
                @sort-change="changeTableSort"
                :resizable-config="{ minWidth: '60' }"
                ref="table"
                show-header-overflow="tooltip"
                show-footer-overflow="tooltip"
                header-align="center"
            >
                <!-- header-align="center"
                footer-align="right" -->
                <vxe-column
                    v-for="item in showFieldList"
                    :field="item.id"
                    :title="item.content"
                    :key="item.content"
                    :align="getAlign(item)"
                    :min-width="item.minWidth || '105px'"
                    show-overflow="tooltip"
                    sortable
                >
                    <template slot-scope="scope">
                        <span v-if="formatParam.includes(item.id)">
                            {{ numberFormat(scope.row[item.id], 2) || '--' }}
                        </span>
                        <span v-else-if="['nav', 'navYesterday', 'totalNav'].includes(item.id)">{{
                            numberFormat(scope.row[item.id], 4) || '--'
                        }}</span>
                        <span v-else>
                            {{ scope.row[item.id] === 0 || (scope.row[item.id] && (scope.row[item.id] + '').trim()) ? scope.row[item.id] : '--' }}
                        </span>
                    </template>
                </vxe-column>
            </vxe-table>
            <risk-pagination :paging="page" @page-change="pageRet"></risk-pagination>
        </div>
        <RiskTableLayout
            title="页面布局"
            :visible.sync="layoutDialog"
            :field-list="tableColumns"
            :selected-field-list="selectedFieldList"
            :fixed-field-list="fixedFieldList"
            table-name="TN_ASSET_FUND_QUERY"
            @on-submit="onSubmit"
        />
    </div>
</template>
<script lang="ts">
import RiskPagination from '@/common/components/risk-pagination.vue';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import { numberFormat } from '@/utils/tools';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import FundQueryCondition from './fund-query-condition.vue';
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}

@Component({ name: 'FundQuery', components: { FundQueryCondition, RiskTableLayout, RiskPagination } })
export default class FundQuery extends Vue {
    isOpen: boolean = false;

    showSearchParams: any = []; // 显示查询字段

    tableData: any[] = [];

    summary: any = {}; // 汇总行

    formatParam = [
        'beginCash',
        'currentCash',
        'basicFrozenBalance',
        'fundTotalValue',
        'fundValue',
        'fundValueYesterday',
        'fundShare',
        'stockAsset',
        'bondAsset',
        'fundAsset',
        'hgAsset',
        'warrantAsset',
        'optionAsset',
        'otherAsset',
        'futuresDeposit',
    ];
    // 排序字段
    sortableObj = {
        fundId: 'L_FUND_ID',
        fundName: 'VC_FUND_NAME',
        fundType: 'C_FUND_TYPE',
        beginCash: 'EN_BEGIN_CASH',
        currentCash: 'EN_CURRENT_CASH',
        basicFrozenBalance: 'EN_BASIC_FROZEN_BALANCE',
        fundTotalValue: 'EN_FUND_TOTAL_VALUE',
        fundValue: 'EN_FUND_VALUE',
        fundValueYesterday: 'EN_FUND_VALUE_YESTERDAY',
        fundShare: 'EN_FUND_SHARE',
        nav: 'EN_NAV',
        navYesterday: 'EN_NAV_YESTERDAY',
        totalNav: 'EN_TOTAL_NAV',
        stockAsset: 'EN_STOCK_ASSET',
        bondAsset: 'EN_BOND_ASSET',
        fundAsset: 'EN_FUND_ASSET',
        hgAsset: 'EN_HG_ASSET',
        warrantAsset: 'EN_WARRANT_ASSET',
        optionAsset: 'EN_OPTION_ASSET',
        otherAsset: 'EN_OTHER_ASSET',
        futuresDeposit: 'EN_FUTURES_DEPOSIT',
        currentCashPercent: 'TO_NUMBER(currentCashPercent)',
        stockAssetPercent: 'TO_NUMBER(stockAssetPercent)',
        bondAssetPercent: 'TO_NUMBER(bondAssetPercent)',
        fundAssetPercent: 'TO_NUMBER(fundAssetPercent)',
        hgAssetPercent: 'TO_NUMBER(hgAssetPercent)',
        warrantAssetPercent: 'TO_NUMBER(warrantAssetPercent)',
        optionAssetPercent: 'TO_NUMBER(optionAssetPercent)',
        otherAssetPercent: 'TO_NUMBER(otherAssetPercent)',
        currencyNo: 'VC_CURRENCY_NO',
    };

    tableColumns = [
        { content: '产品序号', id: 'fundId', align: 'left' },
        { content: '产品名称', id: 'fundName', align: 'left' },
        { content: '产品类型', id: 'fundType', align: 'center' },
        { content: '期初资金余额', id: 'beginCash', minWidth: '130px' },
        { content: '当前资金余额', id: 'currentCash', minWidth: '130px' },
        { content: '保证金 ', id: 'basicFrozenBalance' },
        { content: '基金总资产', id: 'fundTotalValue', minWidth: '120px' },
        { content: '基金净资产', id: 'fundValue', minWidth: '120px' },
        { content: '基金昨日净资产', id: 'fundValueYesterday', minWidth: '150px' },
        { content: '基金总份额', id: 'fundShare', minWidth: '120px' },
        { content: '基金单位净值', id: 'nav', minWidth: '130px' },
        { content: '基金昨日单位净值', id: 'navYesterday', minWidth: '160px' },
        { content: '累计单位净值', id: 'totalNav', minWidth: '130px' },
        { content: '股票资产', id: 'stockAsset' },
        { content: '债券资产', id: 'bondAsset' },
        { content: '基金资产', id: 'fundAsset' },
        { content: '回购资产', id: 'hgAsset' },
        { content: '权证资产', id: 'warrantAsset' },
        { content: '期权资产', id: 'optionAsset' },
        { content: '其他资产', id: 'otherAsset' },
        { content: '期货保证金', id: 'futuresDeposit', minWidth: '120px' },
        { content: '币种', id: 'currencyNo', align: 'left' },
        { content: '当前资金余额占净值(%)', id: 'currentCashPercent', minWidth: '200px', align: 'right' },
        { content: '股票资产占净值比(%)', id: 'stockAssetPercent', minWidth: '185px', align: 'right' },
        { content: '债券资产占净值比(%)', id: 'bondAssetPercent', minWidth: '185px', align: 'right' },
        { content: '基金资产占净值比(%)', id: 'fundAssetPercent', minWidth: '185px', align: 'right' },
        { content: '回购资产占净值比(%)', id: 'hgAssetPercent', minWidth: '185px', align: 'right' },
        { content: '权证资产占净值比(%)', id: 'warrantAssetPercent', minWidth: '185px', align: 'right' },
        { content: '期权资产占净值比(%)', id: 'optionAssetPercent', minWidth: '185px', align: 'right' },
        { content: '其他资产占净值比(%)', id: 'otherAssetPercent', minWidth: '185px', align: 'right' },
    ];

    private page: pages = {
        currentPage: 1,
        pageSize: 25,
        total: 0,
    };

    private sortProp: string = 'fundId'; // 排序字段

    private sortOrder: string = 'asc'; // 排序方式

    sort: string = 'L_FUND_ID ASC'; // 默认排序字段

    numberFormat = numberFormat;

    layoutDialog: boolean = false; // 布局显示值

    showFieldList: any[] = []; // 展示字段

    selectedFieldList: any[] = []; // 已选字段

    fixedFieldList: any[] = [{ id: 'fundId', content: '产品序号', align: 'left' }];

    searchParam: any = {}; // 查询条件

    loading: boolean = false; // 页面渲染

    tableKey: number = -1;

    isFirst: boolean = true;

    @Prop() activeValue: string;

    @Watch('activeValue', { immediate: true })
    async handleActiveValue() {
        if (this.activeValue === 'fund-query') {
            if (this.isFirst) {
                await this.queryLayout();
                this.getFundQueryTableData();
                this.isFirst = false;
            }
        }
    }

    getFundQueryTableData() {
        this.loading = true;
        return new Promise((resolve, reject) => {
            this.$axios
                .post('/productSelect/list', {
                    paging: {
                        currentPage: this.page.currentPage,
                        pageSize: this.page.pageSize,
                    },
                    ...this.searchParam,
                })
                .then((res: any) => {
                    if (res.total) {
                        this.summary = res.list[res.list.length - 1];
                        this.tableData = res.list.slice(0, res.list.length - 1);
                    } else {
                        this.tableData = [];
                    }
                    this.page.total = res.total;
                    this.loading = false;
                    resolve(res);
                })
                .catch(err => {
                    this.loading = false;
                    reject(err);
                });
        });
    }

    // 查询回调
    comReturn(obj) {
        this.isOpen = obj.isOpen;
        this.searchParam = obj.searchParam;
    }

    // 分页页面返回处理
    pageRet() {
        this.getFundQueryTableData();
    }

    // 分页
    pageChange(curPage: number): void {
        this.page.currentPage = curPage;
        this.getFundQueryTableData();
    }

    // 合计行
    getSummaries() {
        let arr = [];
        if (this.tableData.length) {
            let count = 0;
            let obj = this.tableData[0];
            let objR = this.summary;
            for (let item of this.showFieldList) {
                if (objR[item.id]) {
                    arr[count++] = numberFormat(objR[item.id], 2);
                } else {
                    arr[count++] = '--';
                }
            }
            console.log([arr]);
        }
        return [arr];
    }
    // 排序改变
    private changeTableSort(column): void {
        this.sortProp = column.property;
        this.sortOrder = column.order;
        let sortType = column.order == 'asc' ? 'ASC' : column.order == 'desc' ? 'DESC' : '';
        this.searchParam.sort = this.sortableObj[column.property] + ' ' + sortType;
        this.pageChange(1);
    }

    /**
     * 提交成功后回调
     * @param {Object} 回调数据
     */
    async onSubmit(data) {
        await this.queryLayout();
    }

    // 获取页面布局信息
    async queryLayout() {
        let resList: any = await new Promise((resolve, reject) => {
            this.$axios('/tableLayout/query/TN_ASSET_FUND_QUERY')
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });

        if (!resList) {
            // 新用户初始化
            this.showFieldList = this.tableColumns;
            const fixKeys = this.fixedFieldList.map(item => item.id);
            this.selectedFieldList = this.showFieldList.filter(item => !fixKeys.includes(item.id));
        } else {
            if (resList.length < 1) {
                // 选项为空
                this.showFieldList = this.fixedFieldList;
                this.selectedFieldList = [];
            } else {
                this.selectedFieldList = JSON.parse(resList);
                this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);
                // const temps = this.fixedFieldList.concat(JSON.parse(resList)).map(item => item.id);
                // this.showFieldList = this.tableColumns.filter(item => temps.includes(item.id));
            }
        }

        this.tableKey++;
    }

    // 按钮点击
    handleButton(type): void {
        if (type == 'search') {
            this.pageChange(1);
        } else if (type == 'refresh') {
            this.pageChange(1);
        } else if (type == 'doLayout') {
            this.layoutDialog = true;
        }
    }

    getCellStyle({ column }) {
        let value = 'padding: 0; text-align:right';
        let obj = this.tableColumns.find(item => item.id == column.property);
        if (obj) {
            value = 'padding: 0; text-align: ' + (obj.align || 'right');
        }
        return value;
    }

    getAlign(ele) {
        let obj = this.tableColumns.find(item => item.id == ele.id);
        return (obj && obj.align) || 'right';
    }
}
</script>
<style lang="scss" scoped>
@import '@/project/pyaxa/pages/report/styles/common';

/deep/ .vxe-table {
    .vxe-table--body-wrapper.body--wrapper {
        height: calc(100vh - 265px);
    }
}
</style>
